package com.aduerr.v1shouyin.mvp.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.SellerListEntity;
import com.aduerr.v1shouyin.entity.ShopListEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.util.DoubleClickUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.orhanobut.hawk.Hawk;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * 对账里面的门店、收银员、最近几天的列表
 */
public class HomeBillSelectActivity extends AppCompatActivity {
    @BindView(R.id.img_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.et_search_input)
    EditText mEtSearchInput;
    @BindView(R.id.rv_bill_select)
    RecyclerView mRecyclerView;
    public int selectType = 0;
    public int groupId;
    public int shopId;
    public int sellerId;
    List<ShopListEntity.DataBean> shopList = new ArrayList<>();
    List<SellerListEntity.DataBean> sellerList = new ArrayList<>();
    //用于输入框自动检索
    SellerListEntity sellerListEntity;
    ShopListEntity shopListEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_bill_selecte);
        ButterKnife.bind(this);
        selectType = getIntent().getIntExtra("select_type", 0);
        if(selectType == 0) {
            getShopList(1);
        } else {
            getSellerList(1);
        }
        initView();

    }


    public void initView() {
        mTvTitle.setText(selectType == 0 ? "门店列表" : "收银员列表");
        mEtSearchInput.setHint(selectType == 0 ? "请输入门店名称" : "请输入收银员名称");
        mEtSearchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String input = mEtSearchInput.getText().toString().trim();
                if(TextUtils.isEmpty(s)) {
                    if(selectType == 0) {
                        if(shopListEntity == null || shopListEntity.getData() == null) {
                            return;
                        }
                        shopList.clear();
                        for(int i = 0; i < shopListEntity.getData().size(); i++) {
                            shopList.add(shopListEntity.getData().get(i));
                        }
                        //门店
                        setShopListAdapter();
                    } else {
                        if(sellerListEntity == null || sellerListEntity.getData() == null) {
                            return;
                        }
                        sellerList.clear();
                        for(int i = 0; i < sellerListEntity.getData().size(); i++) {
                            sellerList.add(sellerListEntity.getData().get(i));
                        }
                        setSellerAdapter();
                    }
                } else {
                    if(selectType == 0) {
                        if(shopListEntity == null || shopListEntity.getData() == null) {
                            return;
                        }
                        //门店
                        shopList.clear();
                        for(int i = 0; i < shopListEntity.getData().size(); i++) {
                            if(shopListEntity.getData().get(i).getShopName().contains(input)) {
                                shopList.add(shopListEntity.getData().get(i));
                            }

                        }
                        setShopListAdapter();
                    } else {
                        if(sellerListEntity == null || sellerListEntity.getData() == null) {
                            return;
                        }
                        sellerList.clear();
                        for(int i = 0; i < sellerListEntity.getData().size(); i++) {
                            if(sellerListEntity.getData().get(i).getName().contains(input)) {
                                sellerList.add(sellerListEntity.getData().get(i));
                            }

                        }
                        setSellerAdapter();
                    }

                }
            }
        });
    }

    @OnClick({R.id.img_back})
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.img_back:
                if(!DoubleClickUtils.isFastDoubleClick(R.id.img_back)) {
                    finish();
                }
                break;
        }
    }


    /**
     * 收银员
     */
    private void getSellerList(int page) {

        HashMap<String, String> addParams = new HashMap<>();
        //======================权限判断============================
        String userType = Hawk.get("level");
        if(userType.equals("收银员") || userType.equals("客服")) {
            return;
        }
        //=======================权限判断==========================
        addParams.put("pageIndex", "1");
        addParams.put("pageSize", "10000");

        APIRetrofit.getAPIService().getSellerlist(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())//开启一个io线程
                .observeOn(AndroidSchedulers.mainThread())//回到主线程
                .subscribe(new Observer<SellerListEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(SellerListEntity entity) {
                        if(entity != null && entity.getData() != null && entity.getData().size() > 0) {
                            SellerListEntity.DataBean dataBean =
                                    new SellerListEntity.DataBean();
                            dataBean.setID(0);
                            dataBean.setName("全部收银员");
                            entity.getData().add(0, dataBean);
                            sellerList.clear();
                            sellerList.addAll(entity.getData());
                            setSellerAdapter();
                            sellerListEntity = entity;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showToast(HomeBillSelectActivity.this,
                                e.getMessage() + "");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    /**
     * 得到门店列表 只有财务专员有这权限
     */
    public void getShopList(int page) {
        //======================权限判断============================
        String userType = Hawk.get("level");
        if(!userType.equals("财务专员")) {
            return;
        }
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("pageIndex", "1");
        addParams.put("pageSize", "10000");
        addParams.put("shopid", "0");
        APIRetrofit.getAPIService().getShopList(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())//开启一个io线程
                .observeOn(AndroidSchedulers.mainThread())//回到主线程
                .subscribe(
                        new Observer<ShopListEntity>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(ShopListEntity entity) {
                                if(entity != null && entity.getData() != null && entity.getData().size() > 0) {
                                    ShopListEntity.DataBean dataBean =
                                            new ShopListEntity.DataBean();
                                    dataBean.setID(0);
                                    dataBean.setShopName("全部门店");
                                    entity.getData().add(0, dataBean);
                                    shopList.clear();
                                    shopList.addAll(entity.getData());
                                    setShopListAdapter();
                                    shopListEntity = entity;
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        }
                );
    }


    private BaseQuickAdapter<SellerListEntity.DataBean, BaseViewHolder> sellerAdapter;

    public void setSellerAdapter() {
        if(sellerAdapter == null) {
            sellerAdapter =
                    new BaseQuickAdapter<SellerListEntity.DataBean, BaseViewHolder>(R.layout.item_select_shop_seller, sellerList) {
                        @Override
                        protected void convert(BaseViewHolder helper,
                                               SellerListEntity.DataBean item) {
                            helper.setText(R.id.tv_shop_seller, item.getName());

                        }
                    };


            sellerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view,
                                        int position) {
                    String sellerId = sellerList.get(position).getID() + "";
                    String sellerName = sellerList.get(position).getName();
                    Intent intent = getIntent();
                    intent.putExtra("seller_id", sellerId);
                    intent.putExtra("seller_name", sellerName);
                    HomeBillSelectActivity.this.setResult(67, intent);
                    HomeBillSelectActivity.this.finish();

                }
            });
            mRecyclerView.setHasFixedSize(true);
            mRecyclerView.setNestedScrollingEnabled(false);
            LinearLayoutManager manager = new LinearLayoutManager(this,
                    LinearLayoutManager.VERTICAL, false);

            mRecyclerView.setLayoutManager(manager);
            mRecyclerView.setAdapter(sellerAdapter);
        } else {
            sellerAdapter.notifyDataSetChanged();
        }
    }


    private BaseQuickAdapter<ShopListEntity.DataBean, BaseViewHolder> shopListAdapter;

    public void setShopListAdapter() {
        if(shopListAdapter == null) {
            shopListAdapter = new BaseQuickAdapter<ShopListEntity.DataBean,
                    BaseViewHolder>(R.layout.item_select_shop_seller, shopList) {
                @Override
                protected void convert(BaseViewHolder helper,
                                       ShopListEntity.DataBean item) {
                    helper.setText(R.id.tv_shop_seller, item.getShopName());

                }
            };


            shopListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view,
                                        int position) {
                    String shopId = shopList.get(position).getID() + "";
                    String shopName = shopList.get(position).getShopName();
                    Intent intent = getIntent();
                    intent.putExtra("shop_id", shopId);
                    intent.putExtra("shop_name", shopName);
                    HomeBillSelectActivity.this.setResult(66, intent);
                    HomeBillSelectActivity.this.finish();

                }
            });
            mRecyclerView.setHasFixedSize(true);
            mRecyclerView.setNestedScrollingEnabled(false);
            LinearLayoutManager manager = new LinearLayoutManager(this,
                    LinearLayoutManager.VERTICAL, false);

            mRecyclerView.setLayoutManager(manager);
            mRecyclerView.setAdapter(shopListAdapter);
        } else {
            shopListAdapter.notifyDataSetChanged();
        }
    }

}

